const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

exports.main = async (event, context) => {
  console.log('📊 获取审核统计数据')
  
  try {
    // 获取今天的开始时间
    const today = new Date()
    today.setHours(0, 0, 0, 0)
    
    // 获取明天的开始时间
    const tomorrow = new Date(today)
    tomorrow.setDate(tomorrow.getDate() + 1)
    
    // 并行查询各种统计数据
    const [
      pendingResult,
      approvedResult,
      rejectedResult,
      allResult,
      approvedTodayResult,
      rejectedTodayResult
    ] = await Promise.all([
      // 待审核数量
      db.collection('construction_teams')
        .where({ auditStatus: 'pending' })
        .count(),
      
      // 已通过数量
      db.collection('construction_teams')
        .where({ auditStatus: 'approved' })
        .count(),
      
      // 已拒绝数量
      db.collection('construction_teams')
        .where({ auditStatus: 'rejected' })
        .count(),
      
      // 总数量
      db.collection('construction_teams')
        .count(),
      
      // 今日通过数量
      db.collection('construction_teams')
        .where({
          auditStatus: 'approved',
          auditTime: db.command.gte(today).and(db.command.lt(tomorrow))
        })
        .count(),
      
      // 今日拒绝数量
      db.collection('construction_teams')
        .where({
          auditStatus: 'rejected',
          auditTime: db.command.gte(today).and(db.command.lt(tomorrow))
        })
        .count()
    ])
    
    const stats = {
      pendingCount: pendingResult.total,
      approvedCount: approvedResult.total,
      rejectedCount: rejectedResult.total,
      allCount: allResult.total,
      approvedToday: approvedTodayResult.total,
      rejectedToday: rejectedTodayResult.total
    }
    
    console.log('✅ 统计数据获取成功:', stats)
    
    return {
      success: true,
      data: stats
    }
    
  } catch (error) {
    console.error('❌ 获取统计数据失败:', error)
    return {
      success: false,
      error: error.message || '获取统计数据失败'
    }
  }
}
